import { onBeforeUnmount, onMounted, reactive, ref } from "vue"
import { downfileUrl } from "@/utils"
export function useAudio(params = {}) {
	const useAudioState = reactive({
		isPlayTopicAudio: false,
		isPlayResultAudio: false
	})
	let remindAudioContext = null
	// 文字转语音
	var plugin = requirePlugin("WechatSI")
	const innerAudioContext = wx.createInnerAudioContext({ useWebAudioImplement: true });
	const rowData = ref({})
	const audioList = ref([])
	const audioArrayIdx = ref(0)
	const audioArrayModule = ref(false)
	
	onMounted(() => {
	})
	
	onBeforeUnmount(() => {
		useDestroy()
	})
	
	const useDestroy = (params = {}) => {
		remindAudioContext && remindAudioContext.destroy()
		remindAudioContext = null
		params.create && create()
	}
	const create = () => {
		// useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
		remindAudioContext = wx.createInnerAudioContext()
		remindAudioContext.onPlay((e)=>{})
		remindAudioContext.onStop((e)=>{})
		remindAudioContext.onEnded((e)=>{
			// 题目音频
			if(useAudioState.isPlayTopicAudio) {
				audioArrayIdx.value++
				usePlayOnly()
			}
			// 结果回调
			if(useAudioState.isPlayResultAudio) {
				params.end && params.end(rowData.value)
			}
		})
		remindAudioContext.onError((e)=>{
			params.error && params.error(rowData.value)
		})
	}
	
	/**
	 * 播放题目音频
	 */
	const useIsPlayTopicAudio = (value) => useAudioState.isPlayTopicAudio = value
	
	/**
	 * 播放结果音频
	 */
	const useIsPlayResultAudio = (value) => useAudioState.isPlayResultAudio = value
	
	/**
	 * 获取音频
	 */
	const usePlayText = (words) => {
		return new Promise((resolve, reject) => {
			wordsToAudio(words).then(audio => {
				innerAudioContext.autoplay = true;
				//设置音频地址
				innerAudioContext.src = audio;
				//播放音频
				innerAudioContext.play();
				resolve()
				state.isAudioPlay = false
			}).catch(() => {
				reject()
			})
		})
	}
	
	const wordsToAudio = (words) => {
		return new Promise((resolve, reject) => {
			plugin.textToSpeech({
				lang: "zh_CN",
				tts: true,
				content: words,
				success: (res) => {
					resolve(res.filename)
				},
				fail: (res) => {
				},
			});
		})
	}
    
	const usePlay = (url, row) => {
		return new Promise((resolve, reject) => {
			useDestroy({create: true})
			// 数据
			rowData.value = row
			// https
			const isHttps = url.indexOf('https') !== -1
			if(url && !isHttps) {
				remindAudioContext.src = url
				remindAudioContext.play()
				return
			}
			downfileUrl(url).then(res => {
				remindAudioContext.src = res.data.tempFilePath
				remindAudioContext.play()
				params.success && params.success(rowData.value)
				resolve(res)
			}).catch(() => {
				params.error && params.error(rowData.value)
				reject()
			})
		})
	}
	/**
	 * 获取远程音频
	 */
	const getAudioUrl = (url) => {
		return new Promise((resolve, reject) => {
			downfileUrl(url).then(res => {
				resolve(res.data.tempFilePath)
			}).catch(() => {
				reject(null)
			})
		})
	}
	/**
	 * 获取远程音频文件，数组
	 */
	const useGetDownloadAudio = (audioUrl) => {
		// 索引
		let idx = 0;
		const resourcesAudio = []
		return new Promise((resolve, reject) => {
			// 递归获取
			function getUrl(){
				if(audioUrl[idx]) {
					const promise = new Promise((resolve, reject) => {
						getAudioUrl(audioUrl[idx]).then(res => {
							idx++
							resourcesAudio.push(res)
							resolve(resolve)
							getUrl()
						}).catch(() => {
							reject()
						})
					})
				}else{
					resolve(resourcesAudio)
				}
			}
			getUrl()
		})
	}
	/**
	 * 播放音频数组
	 */
	const usePlayAudioArray = (audioItem) => {
		audioArrayIdx.value = 0
		audioList.value = audioItem
		useIsPlayTopicAudio(true)
		useDestroy({create: true})
		usePlayOnly()
	}
	const usePlayOnly = () => {
		const filePath = audioList.value[audioArrayIdx.value]
		if(!filePath) {
			audioArrayModule.value = false
			audioArrayIdx.value = 0
			useIsPlayTopicAudio(false)
			params.audioAllEnd && params.audioAllEnd()
			useDestroy()
			return
		}
		remindAudioContext.src = filePath
		remindAudioContext.play()
	}
	
    return {
		useAudioState,
		usePlay,
		usePlayText,
		useDestroy,
		useGetDownloadAudio,
		usePlayAudioArray,
		useIsPlayTopicAudio,
		useIsPlayResultAudio,
		useDestroy
	};
}